package com.ndp.fb.walle.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ndp.ec.core.FbUserService;
import com.ndp.ec.core.UserService;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.model.fbagent.param.serach.SearchParam;
import com.ndp.fb.model.fbagent.param.serach.SearchType;
import com.ndp.fb.model.fbagent.result.common.FBAdInterest;
import com.ndp.fb.model.fbagent.result.common.FBAdLocale;
import com.ndp.fb.model.fbagent.result.common.FBBehaviors;
import com.ndp.fb.model.fbagent.result.common.FBSearchCategoryResult;
import com.ndp.fb.model.fbagent.result.common.FBSearchResult;
import com.ndp.fb.rdb.model.AdGeolocation;
import com.ndp.fb.rdb.model.Dictionary;
import com.ndp.fb.rdb.model.FbUser;
import com.ndp.fb.rdb.model.InterestWord;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.SearchService;
import com.ndp.fb.walle.model.bo.search.result.AdGeolocationBo;
import com.ndp.fb.walle.model.bo.search.result.MoreTargetingCategoryResultBo;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.search.param.BatchSearchParam;
import com.ndp.fb.walle.model.vo.search.param.SearchVoParam;
import com.ndp.fb.walle.model.vo.search.result.BehaviorSon;
import com.ndp.fb.walle.model.vo.search.result.BehaviorVo;
import com.ndp.fb.walle.model.vo.search.result.TargetingCategoryParentVo;
import com.ndp.fb.walle.util.ResponseUtils;

/**
 * Title: SearchController.java Description: SearchController
 *
 * @author Sisi 创建时间 2014年7月18日 下午3:27:52
 */
@RequestMapping("/search")
@Controller
public class SearchController {
    /**
     * 日志
     */
    private final org.slf4j.Logger LOG = LoggerFactory.getLogger(getClass());

    /**
     * searchService
     */
    @Autowired
    private SearchService searchService;

    @Reference
    private FbUserService fbUserService;

    @Reference
    private UserService userService;

    /**
     * 获取语言
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     * @author Sisi 创建时间 2014年7月21日 下午3:35:29
     */
    @RequestMapping("searchAdlocale")
    @ResponseBody
    public ResponseEntity<String> searchAdlocale(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {

        ErrorType errorType = null;
        List<FBAdLocale> data = null;
        LOG.debug("开始查询语言->param->" + param);
        try {
            SearchVoParam srearchParam = JSON.parseObject(param, SearchVoParam.class);
            
            User user = (User) request.getSession().getAttribute("user");
            List<Long> roleIds = userService.getRoleByUser(user.getId());
            User tmpUser = null;
            if (ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_UIDESIGNER) || roleIds.contains(CommonConstants.ROLE_OUTERUIDESIGNER))) {
                tmpUser = userService.getAdminUserByCurrentUser(user.getTicket());

            } else{
                tmpUser = user;
            }

            FbUser fbUser = fbUserService.getFbUser(tmpUser.getTicket());
            String[] langs = srearchParam.getLocale().split(CommonConstants.SYMBOL_LINE);
            //这里回头统一处理当获取不到user
            data = (List<FBAdLocale>) searchService.search(fbUser.getAccessToken(), langs[0]+CommonConstants.SYMBOL_UNDERLINE+langs[1].toUpperCase(), srearchParam.getQ(), srearchParam.getType());

            if (null == data) {
                errorType = ErrorType.SEARCH_ADLOCALE_FAIL;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage());
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 兴趣词搜索
     * @param param              param
     * @param httpServletRequest httpServletRequest
     * @return ResponseEntity<String>
     * @author Sisi 创建时间 2014年7月21日 下午4:16:22
     */
    @RequestMapping("searchInterests")
    @ResponseBody
    public ResponseEntity<String> searchInterests(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        LOG.debug("开始查询兴趣->param->" + param);
        return searchInterestsCommon(param, httpServletRequest);
    }


    /**
     * 查询兴趣建议
     * @param param param
     * @param request request
     * @return
     */
    @RequestMapping("searchInterestSuggestion")
    @ResponseBody
    public ResponseEntity<String> searchInterestSuggestion(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        LOG.debug("开始查询兴趣建议->param->" + param);
        ErrorType errorType = null;
        List<FBAdInterest> data = null;
        try {
            SearchVoParam searchParam = JSON.parseObject(param, SearchVoParam.class);

            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            data = searchService.searchInterestSuggestion(fbUser.getAccessToken(), searchParam.getLocale(), searchParam.getInterestsList());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 查询兴趣类别
     * @param param param
     * @param request request
     * @return
     */
    @RequestMapping("searchInterestsCategory")
    @ResponseBody
    public ResponseEntity<String> searchInterestsCategory(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        LOG.debug("开始查询兴趣类别->param->" + param);
        ErrorType errorType = null;
        List<TargetingCategoryParentVo> data = null;
        try {
            SearchVoParam searchParam = JSON.parseObject(param, SearchVoParam.class);

            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            data = searchService.searchInterestsCategory(fbUser.getAccessToken(), searchParam.getLocale());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(outputResult);
    }

    /**
     * 语言字典
     * @param param
     * @return
     */
    @RequestMapping("getDictionary")
    @ResponseBody
    public ResponseEntity<String> getDictionary(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        List<Dictionary> data = null;
        try {
            User user = (User) request.getSession().getAttribute("user");
            SearchVoParam srearchParam = JSON.parseObject(param, SearchVoParam.class);
            if (srearchParam != null) {
                data = searchService.getDict(srearchParam.getType(), user.getLanguage());
                if (ListUtil.isEmpty(data))
                    data = new ArrayList<>();
            } else {
                errorType = ErrorType.PARAM_EXCEPTION;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage());
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * @param param param
     * @return ResponseEntity<String>
     * @description 查询兴趣相关信息
     * @author Sisi 创建时间 2014年7月21日 下午4:22:10
     */
    private ResponseEntity<String> searchInterestsCommon(String param, HttpServletRequest httpServletRequest) {
        ErrorType errorType = null;
        List<FBAdInterest> data = null;

        try {
            SearchVoParam srearchParam = JSON.parseObject(param, SearchVoParam.class);

            User user = (User) httpServletRequest.getSession().getAttribute("user");
            List<Long> roleIds = userService.getRoleByUser(user.getId());
            User tmpUser;
            if (ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_UIDESIGNER) || roleIds.contains(CommonConstants.ROLE_OUTERUIDESIGNER))) {
                tmpUser = userService.getAdminUserByCurrentUser(user.getTicket());
            } else{
                tmpUser = user;
            }

            FbUser fbUser = fbUserService.getFbUser(tmpUser.getTicket());
            data = (List<FBAdInterest>) searchService.search(fbUser.getAccessToken(), srearchParam.getLocale(), srearchParam.getQ(), srearchParam.getType());

            if (null == data) {
                errorType = ErrorType.SEARCH_INTEREST_FAIL;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage());
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);

        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 查询地区
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     * @author Sisi
     * 创建时间 2014年7月21日 下午4:52:00
     */
    @RequestMapping("searchAdgeolocation")
    public ResponseEntity<String> searchAdgeolocation(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        LOG.debug("开始查询国家和城市->param->" + param);
        ErrorType errorType = null;
        List<AdGeolocationBo> result = new ArrayList<>();
        try {
            SearchVoParam searchParam = JSON.parseObject(param, SearchVoParam.class);

            User user = (User) request.getSession().getAttribute("user");
            List<Long> roleIds = userService.getRoleByUser(user.getId());
            User tmpUser = null;
            if (ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_UIDESIGNER) || roleIds.contains(CommonConstants.ROLE_OUTERUIDESIGNER))) {
                tmpUser = userService.getAdminUserByCurrentUser(user.getTicket());
            } else{
                tmpUser = user;
            }

            FbUser fbUser = fbUserService.getFbUser(tmpUser.getTicket());

            String[] langs = searchParam.getLocale().split(CommonConstants.SYMBOL_LINE);
            List<AdGeolocationBo> data = searchService.searchCountryAndCity(fbUser.getAccessToken(), langs[0]+CommonConstants.SYMBOL_UNDERLINE+langs[1].toUpperCase(), searchParam.getQ(), searchParam.getCType());

            if (ListUtil.isNotEmpty(data)) {
                if (searchParam.getExcludeKeys() != null && searchParam.getExcludeKeys().length > 0) {
                    Map<String, AdGeolocationBo> map = new HashMap<>();
                    for (AdGeolocationBo bo : data) {
                        map.put(bo.getKey(), bo);
                    }
                    Iterator<Map.Entry<String, AdGeolocationBo>> it = map.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, AdGeolocationBo> entry = it.next();
                        if (ArrayUtils.contains(searchParam.getExcludeKeys(), entry.getKey())) {
                            it.remove();
                        }
                    }
                    for (Map.Entry<String, AdGeolocationBo> entry : map.entrySet()) {
                        result.add(entry.getValue());
                    }
                } else {
                    result.addAll(data);
                }
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error("xxxx ", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, result);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));

    }


    /**
     * 查询全量国家
     * @return ResponseEntity<String>
     */
    @RequestMapping("searchALLAdgeolocation")
    public ResponseEntity<String> searchALLAdgeolocation() {
        LOG.debug("开始查询国家和城市->param->" );
        ErrorType errorType = null;
        List<AdGeolocation> adGeolocationList = null;
        try {
            adGeolocationList = searchService.searchALLCountry();
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error("xxxx ", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, adGeolocationList);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));

    }


    /**
     * 批量查询兴趣-粘贴兴趣词
     * @param param
     * @param httpServletRequest
     * @return
     */
    @RequestMapping("searchInterestList")
    @ResponseBody
    public ResponseEntity<String> searchInterestList(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        ErrorType errorType = null;
        List<FBAdInterest> data = null;
        LOG.debug("开始查询兴趣列表->param->" + param);
        try {
            SearchVoParam srearchParam = JSON.parseObject(param, SearchVoParam.class);

            User user = (User) httpServletRequest.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            List<String> interestList = new ArrayList<String>();
            String interestStr = srearchParam.getInterestList();
            StringTokenizer stringTokenizer = new StringTokenizer(interestStr, "[,|，]");
            while (stringTokenizer.hasMoreTokens()) {
                String ss = stringTokenizer.nextToken().trim();
                if (!"".equals(ss)) {
                    interestList.add(ss.replace("'", "\\'"));
                }
            }
            data = (List<FBAdInterest>) searchService.searchInterestList(fbUser.getAccessToken(), srearchParam.getLocale(), srearchParam.getQ(), interestList);

            if (null == data) {
                errorType = ErrorType.SEARCH_INTEREST_FAIL;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage());
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);

        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }


    /**
     * 校验兴趣词
     * @param param
     * @param httpServletRequest
     * @return
     */
    @RequestMapping("adInterestValid")
    @ResponseBody
    public ResponseEntity<String> adInterestValid(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        ErrorType errorType = null;
        List<InterestWord> data = null;
        LOG.debug("开始校验查询词->param->" + param);
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            List<InterestWord> interestWords = JSON.parseArray(param, InterestWord.class);
            data = searchService.adInterestValid(fbUser.getAccessToken(), interestWords);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage());
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult, SerializerFeature.DisableCircularReferenceDetect));
    }

    /**
     * 地区粘贴批量输入
     *
     * @param param
     * @return
     */
    @RequestMapping("searchAdgeolocationList")
    @ResponseBody
    public ResponseEntity<String> searchAdgeolocationList(@RequestParam(value = "param", required = true) String param) {
        ErrorType errorType = null;
        List<AdGeolocationBo> data = null;
        try {
            BatchSearchParam searchParam = JSON.parseObject(param, BatchSearchParam.class);
            String countries = searchParam.getCountries();
            StringTokenizer stringTokenizer = new StringTokenizer(countries, "[,|，]");
            StringBuffer str = new StringBuffer();
            int count = stringTokenizer.countTokens();
            for (int i = 0; i < count; i++) {
                String ss = stringTokenizer.nextToken().trim();
                if ("".equals(ss) || ArrayUtils.contains(searchParam.getExcludeKeys(), ss)) {
                    continue;
                } else {
                    str.append("'");
                    str.append(ss.replace("'", "\\'"));
                    str.append("'");
                    if (i != count - 1) {
                        str.append(",");
                    }
                }
            }
            LOG.info("---------------------str------------- : " + str);
            if (StringUtil.isNotEmpty(str.toString())) {
                data = searchService.searchCountryListByCodes(StringUtil.trimFirstAndLastChar(str.toString(), ','));
            } else {
                data = new ArrayList<>();
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error("XXXX >>> ", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);

        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 查询行为
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     * @description 这应该是search的 公共方法
     * @author Evan
     * 创建时间 2015年1月27日 下午4:52:00
     */
    @RequestMapping("searchBehaviors")
    public ResponseEntity<String> searchBehaviors(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        List<BehaviorVo> data = null;
        try {
            SearchVoParam srearchParam = JSON.parseObject(param, SearchVoParam.class);
            User user = (User) request.getSession().getAttribute("user");
            boolean flag = false;
            SearchParam searchParam = new SearchParam();

            if (srearchParam != null && srearchParam.getLocale() != null && !"".equals(srearchParam.getLocale().trim()))
            {
                String[] langs = srearchParam.getLocale().split(CommonConstants.SYMBOL_LINE);
                searchParam.setLocale(langs[0]+CommonConstants.SYMBOL_UNDERLINE+langs[1].toUpperCase());
            }

            if (srearchParam != null && srearchParam.getQ() != null && !"".equals(srearchParam.getQ().trim()))
                searchParam.setQ(srearchParam.getQ());

            if (srearchParam != null && srearchParam.getType() != null && !"".equals(srearchParam.getType().trim())) {
                //保证传入的search type在我们枚举中存在
                if (SearchType.getSearchType(srearchParam.getType().trim()) != null) {
                    searchParam.setType(srearchParam.getType());
                    flag = true;
                }
            }

            if (srearchParam != null && srearchParam.getClassT() != null && !"".equals(srearchParam.getClassT().trim()))
                searchParam.setClassT(srearchParam.getClassT()); //url 拼接 &class=behaviors

            if (flag) {
                searchParam.setAccessToken(getTokenByUserId(user.getTicket()));
                List<FBBehaviors> result = (List<FBBehaviors>) searchService.search(searchParam);
                if (null == result) {
                    errorType = ErrorType.SEARCH_BEHAVIOR_FAIL;
                }
                data = transferBehaviorVo(result);
            } else {
                data = Collections.emptyList();
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage());
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    private List<BehaviorVo> transferBehaviorVo(List<FBBehaviors> behaviorsList) {
        List<BehaviorVo> result = new ArrayList<>();
        List<BehaviorSon> sonList = new ArrayList<>();
        //先找出有多少一级
        BehaviorVo vo;
        BehaviorSon son;
        Map<String, String> map = new HashMap<>();
        for (FBBehaviors fb : behaviorsList) {
            if (fb.getPath() != null && !"".equals(fb.getPath())) {
                son = new BehaviorSon();
                son.setId(fb.getId());
                son.setName(fb.getName());
                son.setAudienceSize(fb.getAudienceSize());
                son.setParentName(fb.getPath().get(0));
                map.put(fb.getPath().get(0), fb.getPath().get(0));
                sonList.add(son);
            }
        }
        if (ListUtil.isNotEmpty(sonList)) {
            Iterator it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                String value = map.get(key);
                vo = new BehaviorVo();
                vo.setName(value);
                List<BehaviorSon> bSonList = new ArrayList<>();
                for (BehaviorSon so : sonList) {
                    if (so.getParentName().equals(value)) {
                        bSonList.add(so);
                    }
                }
                vo.setSon(bSonList);
                result.add(vo);
            }
        }
        return result;
    }

    /**
     * 通过user.getTicket获得 第一个BM的 accessToken
     *
     * @param userId
     * @return
     */
    private String getTokenByUserId(String userId) {
        return fbUserService.getFbUser(userId).getAccessToken();
    }

    /**
     * 研究领域
     *
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     */
    @RequestMapping("searchAdeducationmajor")
    public ResponseEntity<String> searchAdeducationmajor(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        LOG.debug("开始查询研究领域->param->" + param);
        return searchByQ(param, request);
    }

    /**
     * 学历--学校
     *
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     */
    @RequestMapping("searchAdeducationschool")
    public ResponseEntity<String> searchAdeducationschool(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        LOG.debug("开始查询学校->param->" + param);
        return searchByQ(param, request);
    }

    /**
     * 工作--雇主
     *
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     */
    @RequestMapping("searchAdworkemployer")
    public ResponseEntity<String> searchAdworkemployer(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        LOG.debug("开始查询雇主->param->" + param);
        return searchByQ(param, request);
    }

    /**
     * 工作--职务
     *
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     */
    @RequestMapping("searchAdworkposition")
    public ResponseEntity<String> searchAdworkposition(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        LOG.debug("开始查询职务->param->" + param);
        return searchByQ(param, request);
    }

    /**
     * 查询更多定位类别
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     */
    @RequestMapping("searchAdTargetingCategory")
    public ResponseEntity<String> searchAdTargetingCategory(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        MoreTargetingCategoryResultBo data = null;
        try {
            SearchVoParam searchParam = JSON.parseObject(param, SearchVoParam.class);
            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            String[] langs = searchParam.getLocale().split(CommonConstants.SYMBOL_LINE);
            data = searchService.searchMoreTargetingCategory(fbUser.getAccessToken(), langs[0]+CommonConstants.SYMBOL_UNDERLINE+langs[1].toUpperCase());

            if (null == data) {
                errorType = ErrorType.SEARCH_COUNTRY_FAIL;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    private ResponseEntity<String> searchByQ(String param, HttpServletRequest request) {
        ErrorType errorType = null;
        List<FBSearchResult> data = null;
        try {
            SearchVoParam searchParam = JSON.parseObject(param, SearchVoParam.class);

            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            String[] langs = searchParam.getLocale().split(CommonConstants.SYMBOL_LINE);
            data = searchService.searchByQ(fbUser.getAccessToken(), langs[0]+CommonConstants.SYMBOL_UNDERLINE+langs[1], searchParam.getQ(), searchParam.getType());

            if (null == data) {
                errorType = ErrorType.SEARCH_COUNTRY_FAIL;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
    
    /**
     * 查询更多定位类别
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     */
    @RequestMapping("searchFbAdTargetingCategory")
    public ResponseEntity<String> searchEbAdTargetingCategory(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        List<FBSearchCategoryResult> data = null;
        try {
            SearchVoParam searchParam = JSON.parseObject(param, SearchVoParam.class);
            User user = (User) request.getSession().getAttribute("user");
            FbUser fbUser = fbUserService.getFbUser(user.getTicket());
            String[] langs = searchParam.getLocale().split(CommonConstants.SYMBOL_LINE);
            data = searchService.searchFbAdTargetingCategory(fbUser.getAccessToken(), langs[0]+CommonConstants.SYMBOL_UNDERLINE+langs[1].toUpperCase(), searchParam.getClassT(), searchParam.getQ());

            if (null == data) {
                errorType = ErrorType.SEARCH_COUNTRY_FAIL;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
    
    /**
     * 查询更多定位类别
     * @param param   param
     * @param request request
     * @return ResponseEntity<String>
     */
    @RequestMapping("targetingbrowse")
    public ResponseEntity<String> searchTargetingbrowse(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        List<JSONObject> data = null;
        try {
            SearchVoParam searchParam = JSON.parseObject(param, SearchVoParam.class);
            String[] langs = searchParam.getLocale().split(CommonConstants.SYMBOL_LINE);
            data = searchService.getTargetingBrowse(langs[0]+CommonConstants.SYMBOL_UNDERLINE+langs[1].toUpperCase());
            if (null == data) {
                errorType = ErrorType.SEARCH_COUNTRY_FAIL;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            LOG.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
}
